import { reactive, ref, watch } from "vue";
const useList = (listRequestFn, searchObject, mergeKey = null) => {
	const orgObject = Object.assign({}, searchObject);
	// 加载态
	const loading = ref(false);
	// 当前页
	const currentPage = ref(1);
	// 总数量
	const totalCount = ref(0);
	// 分页大小
	const pageSize = ref(20);

	const list = ref([]);

	const mergeCol = reactive({});
	// 获取列表数据
	const loadData = async () => {
		// 设置加载中
		loading.value = true;
		try {
			const params = { ...searchObject };
			params["pageNum"] = currentPage.value;
			params["pageSize"] = pageSize.value;
			const { data: resData } = await listRequestFn(params);
			useSpanMethod(resData.objList);
			list.value = resData.objList;
			totalCount.value = resData.totalCount;
		} catch (error) {
			console.log("请求出错了", error);
		} finally {
			// 关闭加载中
			loading.value = false;
		}
	};
	// 监听分页数据改变
	watch(
		() => [currentPage, pageSize],
		() => {
			loadData();
		}
	);
	const handleSizeChange = (size) => {
		pageSize.value = size;
		loadData();
	};
	const handleCurrentChange = (page) => {
		currentPage.value = page;
		loadData();
	};
	const resetSearch = () => {
		const keys = Reflect.ownKeys(searchObject);
		keys.forEach((key) => {
			if (key !== "driverGuid") {
				Reflect.set(searchObject, key, orgObject[key] || null);
			}
		});
		currentPage.value = 1;
		loadData();
	};
	const useSpanMethod = (tableData) => {
		if (!mergeKey) {
			return;
		}
		let currentGroupCode = null;
		tableData.forEach((item, index) => {
			if (!item[mergeKey]) return;
			if (item[mergeKey] !== currentGroupCode) {
				// 之前存在
				if (currentGroupCode) {
					mergeCol[currentGroupCode].end = index - 1;
					// if (mergeCol[currentGroupCode].begin === mergeCol[currentGroupCode].end) {
					//     mergeCol[currentGroupCode] = null
					// }
					mergeCol[item[mergeKey]] = {
						begin: index,
						end: null,
					};
					currentGroupCode = item[mergeKey];
				} else {
					// 第一次
					mergeCol[item[mergeKey]] = {
						begin: index,
						end: null,
					};
					currentGroupCode = item[mergeKey];
				}
			}
			if (index === tableData.length - 1) {
				mergeCol[currentGroupCode].end = index;
			}
		});
	};
	return {
		loading,
		list,
		mergeCol,
		currentPage,
		pageSize,
		totalCount,
		loadData,
		handleSizeChange,
		handleCurrentChange,
		resetSearch,
	};
};

export default useList;
